package person.learn.controller.web;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by barton on 16-1-27.
 */
@Controller
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index() {
        return new ModelAndView("login");
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home() {
        return "home";
    }

    @RequestMapping(value = "/forbidden", method = RequestMethod.GET)
    public String forbidden() {
        return "forbidden";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            model.addAttribute("result", "用户名密码为空");
            return "login";
        }

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
            logger.info("用户" + userName + "登陆成功");
            model.addAttribute("result", "登陆成功");
        } catch (UnknownAccountException unknownException) {
            model.addAttribute("result", unknownException.getMessage());
            logger.info("用户" + userName + "登陆失败");
            return "login";
        } catch (IncorrectCredentialsException incorrectException) {
            model.addAttribute("result", incorrectException.getMessage());
            logger.info("用户" + userName + "登陆失败");
            return "login";
        }

        return "home";
    }
}
